package tcpClient;

import java.io.IOException;
import java.util.ArrayList;

import util.SocketManager;

public class TCPClient {

	private SocketManager so;
	
	public TCPClient(String ip, int port) {
		try {
			so = new SocketManager(ip, port);
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	public boolean validate(String user, String pass) {
		String reply;
		try {
			so.write("USER " + user + "\r\n");
			reply = so.read();
			so.write("PASS " + pass + "\r\n");
			reply = so.read();
			if(reply.startsWith("200")) return true;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}
	
	public String[] listfiles(String path){
		ArrayList<String> al = new ArrayList<String>();
		try {
			so.write("LISTFILES " + path + "\r\n");
			String reply = so.read();
			for(;!reply.startsWith("201");){
				al.add(reply);			
				reply = so.read();			
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String[] as = new String[al.size()];
		return al.toArray(as);
	}
	
	public String getInfo(String filename){
		try {
			so.write("GETINFO " + filename + "\r\n");
			String reply = so.read();
			if (reply.startsWith("402"))
				return null;
			else 
				return reply.substring(6);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	public boolean quit(){
		try {
			so.write("QUIT\r\n");
			String reply = so.read();
			if (reply.startsWith("203"))
				return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
